import classNames from 'classnames'
import { memo, useEffect } from 'react'
import { toast } from 'react-toastify'
import { IconFont, IconName } from '../IconFont'
import styles from './Toast.module.scss'
import 'react-toastify/dist/ReactToastify.css'

type ToastType = 'alternative' | 'default' | 'negative' | 'positive'

interface ToastContent {
  message: string
  type: ToastType
}

interface ToastBehavior {
  autoClose?: number
  closeOnClick?: () => void
}

interface ToastProps extends ToastContent, ToastBehavior {}

export const Toast = memo(({ autoClose = 2000, message, type = 'positive' }: ToastProps) => {
  const allStyles = classNames(styles.component, styles[type])

  const closeToast = () => {
    toast.dismiss()
  }

  const closeOnClick = () => {
    closeToast()
  }

  useEffect(() => {
    const timeout = setTimeout(closeToast, autoClose)

    return () => {
      clearTimeout(timeout)
    }
  }, [autoClose])

  const iconMap: Record<ToastType, { check: IconName; close: IconName }> = {
    alternative: { check: 'icon-achtung-octagon', close: 'icon-close' },
    default: { check: 'icon-achtung-octagon', close: 'icon-close' },
    negative: { check: 'icon-achtung-triangle', close: 'icon-close' },
    positive: { check: 'icon-check', close: 'icon-close' },
  }

  const iconName = iconMap[type]

  return (
    <div className={allStyles}>
      <div className={styles.content}>
        <IconFont iconName={iconName.check} />
        {message}
      </div>
      <div onClick={closeOnClick}>
        <IconFont iconName={iconName.close} />
      </div>
    </div>
  )
})

Toast.displayName = 'Toast'
